import axios from 'axios'
import qs from 'qs'
import { ElMessage } from 'element-plus';
import { router } from './../router'

let server = axios.create({
    baseURL: import.meta.env.DEV ? 'http://school.kouhigh.top' : 'http://school.kouhigh.top'
})

server.interceptors.request.use(config => {
    let token = undefined;
    if(sessionStorage.user_info) {
        token = JSON.parse(sessionStorage.user_info).key
    }
    if(config.method === 'get') {
        if(!config.params) {
            config.params = {};
        }
        config.params.token = token
    } else if(config.method === 'post') {
        if(!config.data) {
            config.data = {}
        }
        config.data.token = token
        config.data = qs.stringify(config.data)
    }
    return config
})

server.interceptors.response.use(config => {
    if(config.data.code === 1001) {
        router.push({path: '/login', query: {company_id: sessionStorage.user_info? JSON.parse(sessionStorage.user_info).manage_id : 1}})
    } else if(config.data.code !== 1000) {
        ElMessage.error({
            type: 'error',
            message: config.data.msg
        })
    }
    return config
}, () => {
    ElMessage.error({
        type: 'error',
        message: '请求失败'
    })
})

export default server